﻿#region MIT
/*
Green.Logging
Part of Engine Of Evermore (http://code.google.com/p/engineofevermore/)
Copyright (c) 2008 Michael Woerister

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace Green.Logging
{
    public sealed class LogFile : IDisposable
    {
        TextWriter _textWriter;
        bool _disposed;
        StringBuilder _stringBuilder = new StringBuilder();

        public LogFile( String appDataPath )
        {
            if ( appDataPath[appDataPath.Length-1] != 
                Path.DirectorySeparatorChar )
            {
                appDataPath += Path.DirectorySeparatorChar;
            }

            FileStream fileStream;

            // Try to create a new file in the working directory
            try
            {
                fileStream = new FileStream(
                    "EngineOfEvermoreLog.txt",
                    FileMode.CreateNew,
                    FileAccess.Write,
                    FileShare.Read
                    );
            }
            catch
            {
                fileStream = null;
            }

            // If that has failed try to open and truncate an existing file
            // in the working directory
            if ( fileStream == null )
            {
                try
                {
                    fileStream = new FileStream(
                        "EngineOfEvermoreLog.txt",
                        FileMode.Truncate,
                        FileAccess.Write,
                        FileShare.Read
                        );
                }
                catch
                {
                    fileStream = null;
                }
            }

            // If that has failed too try repeat the above steps in the 
            // AppData directory
            if ( fileStream == null )
            {
                try
                {
                    fileStream = new FileStream(
                        Path.Combine( appDataPath, "EngineOfEvermoreLog.txt" ),
                        FileMode.CreateNew,
                        FileAccess.Write,
                        FileShare.Read
                        );
                }
                catch
                {
                    fileStream = null;
                }
            }

            if ( fileStream == null )
            {
                try
                {
                    fileStream = new FileStream(
                        Path.Combine( appDataPath, "EngineOfEvermoreLog.txt" ),
                        FileMode.Truncate,
                        FileAccess.Write,
                        FileShare.Read
                        );
                }
                catch
                {
                    fileStream = null;
                }
            }

            Debug.Assert( fileStream != null );

            _textWriter = new StreamWriter( fileStream );

            _textWriter.WriteLine( "||====================================================================||" );
            _textWriter.WriteLine( "|| ENGINE OF EVEMORE LOG FILE                                         ||" );
            _textWriter.WriteLine( "||====================================================================||" );
            _textWriter.WriteLine();

            Log.EntryAdded += new LogEntryAddedDelegate( _logEntryAdded );
        }

        void _logEntryAdded( LogEntry entry )
        {
            _stringBuilder.Length = 0;

            switch ( entry.Type )
            {
                case LogEntryType.Info:  _stringBuilder.Append( "INFO:  " ); break;
                case LogEntryType.Warning:  _stringBuilder.Append( "WARN:  " ); break;
                case LogEntryType.Error: _stringBuilder.Append( "ERROR: " ); break;
            }

            _stringBuilder.Append( entry.Message );

            _textWriter.WriteLine( _stringBuilder.ToString() );
        }

        ~LogFile()
        {
            Dispose( false );
        }

        public void Dispose()
        {
            Dispose( true );
            GC.SuppressFinalize( this );
        }

        public void Dispose( bool disposing )
        {
            if ( !_disposed )
            {
                if ( disposing )
                {
                    if ( _textWriter != null )
                    {
                        _textWriter.Close();
                        _textWriter = null;
                    }

                    Log.EntryAdded -= _logEntryAdded;
                }

                _disposed = true;
            }
        }
    }
}
